package org.dromara.web.CssUtil;

import lombok.extern.slf4j.Slf4j;
import org.dromara.app.cssUtils.RedisServiceUtils;
import org.dromara.app.domain.SkYueDanOrder;
import org.dromara.app.service.ISkAppUserService;
import org.dromara.app.service.ISkYueDanOrderService;
import org.dromara.common.redis.utils.RedisUtils;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * 使用redis 缓存失效监听会有一定的延迟， 过期事件是在redis服务器删除键的时候生成的，而不是在理论上生存时间到达0值得时候生成的，
 *
 * @author jinyi
 * @date 2023/11/25 16:40
 * @desc
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    private final ISkYueDanOrderService iSkYueDanOrderService;

    private final ISkAppUserService iSkAppUserService;

    private final CssOrderServer cssOrderServer;


    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer, ISkYueDanOrderService iSkYueDanOrderService, ISkAppUserService iSkAppUserService,CssOrderServer cssOrderServer) {
        super(listenerContainer);
        this.iSkYueDanOrderService = iSkYueDanOrderService;
        this.iSkAppUserService = iSkAppUserService;
        this.cssOrderServer = cssOrderServer;
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     *
     * @param message key的信息，并不包含缓存值。
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //todo 后续的业务处理
        String keyString = message.toString().split(":")[0];
//        if (RedisServiceUtils.getDaijiedantuikuanTitle().equals(keyString)){
//            System.out.println("没人接单自动取消："+message.toString().split(":")[1]);
//            iSkYueDanOrderService.cencelOrder(message.toString().split(":")[1]);
//        }
        //在线用户清除
        if (RedisServiceUtils.getOnlineUsersTime().equals(keyString)){
            System.out.println("在线用户退出登录："+message.toString().split(":")[1]);
            iSkAppUserService.delUserInfo(message.toString().split(":")[1]);

        }
//        if(true){
//            System.out.println("结束时间已到，自动完成约单");
//        }
        //离线
        if (RedisServiceUtils.loginTokenTitle().equals(keyString)){
            RedisUtils.delCacheMapValue("online-users",message.toString().split(":")[1]);
        }

        //约单信息判断
        if (RedisServiceUtils.getYueDanOrder().equals(keyString)){
            System.out.println("约单订单到期处理约单订单："+message.toString().split(":")[1]);
            SkYueDanOrder orders = iSkYueDanOrderService.daoqiOrderInfo(message.toString().split(":")[1]);
            //分配金额
            if (orders.getState().longValue()==4){
                cssOrderServer.memberDistributionCommissionOrder(orders);
            }

        }
    }

}

